package com.leigang.springboot.jwt.springbootjwt.controller;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.security.Key;
import java.util.HashMap;
import java.util.Map;

@RestController
public class DemoController {
    Key key = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    @GetMapping("/encrypt/{str}")
    public Map index(@PathVariable("str") String str){
        String jws = Jwts.builder().setSubject(str).signWith(key).compact();
        return this.returnCommon("200","success",jws);
    }

    @GetMapping("/decrypt/{code}")
    public Map indexs(@PathVariable("code") String code){
        String result = Jwts.parser().setSigningKey(key).parseClaimsJws(code).getBody().getSubject();
        return this.returnCommon("200","success",result);
    }

    private Map returnCommon(String code, String messaage, Object data){
        Map map = new HashMap(16);
        map.put("code", code);
        map.put("message", messaage);
        map.put("data",data);
        return map;
    }
}
